package com.maike.babyname.base;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.ViewGroup;


import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import com.maike.babyname.utils.LogUtils;

import butterknife.ButterKnife;


public abstract class BaseMvpFragment<P extends BaseFragmentPresenter> extends Fragment {


    protected android.view.View mRootView;
    /**
     * 是否已经加载过，如果已经加载过，说明不是第一次可见
     */
    protected boolean mIsLoaded;
    /**
     * 当前fragment是否可见
     */
    protected boolean mIsVisible;
    /**
     * 是否已经创建好view
     */
    protected boolean mIsCreateView;

    protected P mPresenter;
    protected Activity context;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        mIsVisible = isVisibleToUser;
        LogUtils.e("setUserVisibleHint----mIsLoaded---" + !mIsLoaded + "-----isVisibleToUser---" + isVisibleToUser + "-----mIsCreateView-----" + mIsCreateView);
        if (!mIsLoaded && isVisibleToUser && mIsCreateView) {
            //第一次可见
            lazyLoad();
            mIsLoaded = true;
        }
    }


    @Nullable
    @Override
    public android.view.View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable android.os.Bundle savedInstanceState) {
        context = getActivity();
        if (mRootView != null) {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null) {
                parent.removeView(mRootView);
            }
        }
        mRootView = createView(inflater);
        ButterKnife.bind(this, mRootView);
        mIsCreateView = true;
        lazyLoad();
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable android.os.Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mRootView.destroyDrawingCache();
        mRootView = null;
        if (mPresenter != null)
            mPresenter.onDestroy();
    }

    protected void lazyLoad() {
        LogUtils.Debug("lazyLoad----mIsLoaded---" + !mIsLoaded + "-----isVisibleToUser---" + mIsVisible + "-----mIsCreateView-----" + mIsCreateView);

        if (!mIsLoaded && mIsVisible && mIsCreateView) {
            initData();
            initListenter();
            initView();
            mIsLoaded = true;
        }
    }

    public void refrush() {
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    protected abstract android.view.View createView(LayoutInflater inflater);

    protected abstract void initData();

    protected abstract void initListenter();

    protected abstract void initView();


}
